package com.mywork.mvpkodeinxml.common

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.mywork.mvpkodeinxml.base.view.BaseView
import com.mywork.mvpkodeinxml.model.response.BaseEntity
import com.mywork.mvpkodeinxml.model.response.CommonResp
import com.mywork.mvpkodeinxml.rx.BaseCommonFunc
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import com.uber.autodispose.autoDisposable
import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.reactivestreams.Subscriber

/*
* Observable执行
* */
fun <T> Observable<T>.execute(baseView: BaseView, lifecycleOwner: LifecycleOwner, subscriber: Observer<T>) =
    this.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe { baseView.showLoading() }
        .doFinally { baseView.hideLoading() }
        .autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY))
        .subscribe(subscriber)

/*
* Single执行
* */
fun <T> Single<T>.execute(baseView: BaseView, lifecycleOwner: LifecycleOwner, subscriber: SingleObserver<T>) =
    this.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe { baseView.showLoading() }
        .doFinally { baseView.hideLoading() }
        .autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY))
        .subscribe(subscriber)

/*
* Download执行
* */
fun <T> Flowable<T>.execute(baseView: BaseView, lifecycleOwner: LifecycleOwner, subscriber: Subscriber<T>) =
    this.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe { baseView.showLoading() }
        .doFinally { baseView.hideLoading() }
        .autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY))
        .subscribe(subscriber)


/*类型转换
* 把xml嵌套结果解析出来
* */
fun <T : BaseEntity> Observable<CommonResp>.convertCommon(entityClass: Class<*>): Observable<T> {
    return this.flatMap(BaseCommonFunc(entityClass))
}

